package com.sczmgk.hotline_pzh.utils;


import com.sczmgk.hotline_pzh.annotation.SearchName;

import java.lang.reflect.Field;
import java.util.List;

public class SearchListUtils {
    /**
     * 获取与搜索输入框匹配的数据
     *
     * @param metaLists        原数据
     * @param displayLists     显示的数据
     * @param input            搜索的文字
     * @param isNullInputClear 空输入时是否显示全部内容
     */
    public static <T> void changeDisplayList(List<T> metaLists, List<T> displayLists, String input, boolean isNullInputClear) {

        if (metaLists == null) {
            throw new NullPointerException("metaLists  is  null !");
        }
        if (displayLists == null) {
            throw new NullPointerException("displayLists  is null !");
        } else {
            displayLists.clear();
        }
        if (input == null || input.equals("")) {
            if (isNullInputClear) {
                displayLists.clear();
            } else {
                displayLists.clear();
                displayLists.addAll(metaLists);
            }
        } else {
            int length = metaLists.size();
            for (int i = 0; i < length; ++i) {
                String content = null;
                T t = metaLists.get(i);
                Class<?> clazz = t.getClass();//得到字节码

                try {
                    String fieldName = null;
                    SearchName annotation = clazz.getAnnotation(SearchName.class);
                    if (annotation != null) {
                        fieldName = annotation.value();
                        if (fieldName != null) {
                            Field field = clazz.getDeclaredField(fieldName);//通过反射拿到字段
                            field.setAccessible(true);
                            content = (String) field.get(t);//这个方法是将字段内容取出自某个对象
                            if (content.contains(input)) {//匹配成功加入集合
                                displayLists.add(metaLists.get(i));
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
